const jwt = require("jsonwebtoken");
const { JWT } = require("../config/config.default");
const fs = require("fs");
const privateKey = fs.readFileSync("keys/private.pem");
const publicKey = fs.readFileSync("keys/public.pem");

exports.generateToken = (user) => {
  return jwt.sign(user, privateKey, {
    algorithm: "RS256",
    expiresIn: JWT.expireIn,
  });
};

exports.verifyToken = (req, res, next) => {
  const authorization = req.headers.authorization;
  if (!authorization) return res.send(403, "请先登录");
  const [_, token] = authorization?.split("Bearer ");
  if (token) {
    try {
      const user = jwt.verify(token, publicKey);
      req.user = user;
      next();
    } catch (error) {
      res.send(400, {
        error,
      });
    }
  } else {
    res.send(403, "请先登录");
  }
};

exports.transferToken = (req, res, next) => {
  const [_, token] = req.headers.authorization?.split("Bearer") || [];
  if (token) {
    this.verifyToken(req, res, next);
  } else {
    next();
  }
};
